package com.m4399.ea.sdk;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
 * @author ChenBaoyang
 * @description: EASecurityCheck
 * @date 2021/9/13 13:26
 */
public class EASecurityCheck {

    private static final String HOST = "https://m.4399api.com/openapiv2/open-md5.html";
    private static final String HOST_TEST = "https://m.4399api.com/openapiv2/open-md5.html?is_test=1";

    public void onCheck(String gameKey, String packageName, String version, String secret_key, String md5, final OnCheckListener listener) {
        ThreadPoolUtil.execute(new Runnable() {
            @Override
            public void run() {
                long timestamp = System.currentTimeMillis() / 1000;
                String content = "/open-md5.html&";
                content += timestamp + "&";
                content += secret_key + "&";
                content += "gamekey=" + gameKey + "&";
                content += "md5=" + md5 + "&";
                content += "package=" + packageName + "&";
                content += "version=" + version;

                //从第11位开始，包含含11位，后面的十个字符(小写字母)
                String sign2 = Md5Utils.md5(content);
                String sign = sign2.substring(10, 20);
                Log.i("EA", "签名原串：content = "+content+"，sign2 = " + sign2 + ", sign = " + sign);
                Map<String, Object> param = new HashMap<>();
                param.put("gamekey", gameKey);
                param.put("package", packageName);
                param.put("version", version);
                param.put("md5", md5);
                param.put("time", timestamp + "");
                param.put("sign", sign);

                Log.i("EA", "gamekey = " + gameKey + ", package = " + packageName+",version = "+version+"," +
                        "md5 = "+md5+",time="+timestamp+",sign="+sign);

                HttpUtils.requestPost(HOST, param,
                        new HttpUtils.OnHttpRequestListener() {
                            @Override
                            public void onResponseSuccess(String response) {
                                try {
                                    if (TextUtils.isEmpty(response)) {
                                        return;
                                    }

                                    JSONObject data = new JSONObject(response);
                                    int code = data.optInt("code");
                                    boolean result = data.optBoolean("result");
                                    String msg = data.optString("message");
                                    if(listener != null) {
                                        listener.onResult(code, msg, result);
                                    }
                                    Log.i("EA", "code = " + code + ", message = " + msg+",result = "+result);
                                } catch (Exception e) {
                                    onResponseError(-1, e.getMessage());
                                }
                            }

                            @Override
                            public void onResponseError(final int code, final String errorMessage) {
                                Log.e("EA", errorMessage);
                                if(listener != null) {
                                    listener.onResult(code, errorMessage, false);
                                }
                            }
                        });
            }

        });
    }

    /**
     * 获取当前应用的Apk文件的md5值，不是签名md5
     * @param context
     * @return
     */
    public String getApkFileMD5(Context context) {
        String md5 = "";
        String path = context.getApplicationContext().getPackageResourcePath();
        File file = new File(path);
        try {
            md5 = getFileMD5String(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return md5;
    }
    /**
     * 获取文件MD5
     * @param file
     */
     public  String getFileMD5String(File file) throws Exception {
        InputStream fis;
        MessageDigest messagedigest = MessageDigest.getInstance("MD5");
        fis = new FileInputStream(file);
        byte[] buffer = new byte[1024];
        int numRead = 0;
        while ((numRead = fis.read(buffer)) > 0) {
            messagedigest.update(buffer, 0, numRead);
        }
        fis.close();
        return byte2Hex(messagedigest.digest());
    }

    /**
     * byte[]转Hex字符串
     * @param b
     * @return
     */
    public String byte2Hex(byte[] b) {
        if (null == b) {
            return null;
        }

        StringBuffer sBuffer = new StringBuffer();
        String sTmep;
        for (int i = 0; i < b.length; i++) {
            sTmep = Integer.toHexString(b[i] & 0xFF);

            if (sTmep.length() == 1){
                sBuffer.append("0");
            }
            sBuffer.append(sTmep.toUpperCase(Locale.getDefault()));
        }

        return sBuffer.toString();
    }


}
